package com.lemon.secondhandplatform.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.lemon.secondhandplatform.BaseApplication;
import com.lemon.secondhandplatform.mode.Comment;
import com.lemon.secondhandplatform.mode.Good;
import com.lemon.secondhandplatform.mode.Order;
import com.lemon.secondhandplatform.mode.Photo;
import com.lemon.secondhandplatform.mode.User;
import com.lemon.secondhandplatform.ui.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 后台服务
 */
public class ShpService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new ShpBinder();
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param listener
     */
    public void login(String username, String password, FindListener<User> listener) {
        BmobQuery<User> query = new BmobQuery<>();
        query.addWhereEqualTo("username", username);
        query.addWhereEqualTo("password", password);
        query.setLimit(1);
        query.findObjects(listener);
    }

    /**
     * 修改用户信息
     *
     * @param user
     */
    public void editUser(final User user) {
        user.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e != null) {
                    ToastUtils.show("当前没有网络，修改失败");
                }
            }
        });
    }

    /**
     * 列出商品
     *
     * @param skip
     * @param listener
     */
    public void listGoods(int skip, FindListener<Good> listener) {
        BmobQuery<Good> query = new BmobQuery<>();
        query.include("seller");
        query.addWhereEqualTo("status", Good.NOT_BOOKED);
        query.setLimit(10);
        query.order("-createdAt");
        query.setSkip(skip);
        query.findObjects(listener);
    }

    /**
     * 查询我的商品
     *
     * @param skip
     * @param listener
     */
    public void listMyGoods(int skip, FindListener<Good> listener) {
        BmobQuery<Good> query = new BmobQuery<>();
        query.include("seller");
        query.addWhereEqualTo("seller", BaseApplication.getUser());
        query.setLimit(10);
        query.order("-createdAt");
        query.setSkip(skip);
        query.findObjects(listener);
    }

    /**
     * 删除商品
     *
     * @param good
     * @param listener
     */
    public void deleteGood(final Good good, final QueryListListener<BatchResult> listener) {
        int status = good.getStatus();
        if (status == Good.BOOKED) {
            ToastUtils.show("商品被预定了，不能进行删除操作");
            return;
        }

        BmobQuery<Photo> query = new BmobQuery<>();
        query.addWhereEqualTo("good", good);
        query.findObjects(new FindListener<Photo>() {
            @Override
            public void done(List<Photo> list, BmobException e) {
                if (e == null) {
                    BmobBatch batch = new BmobBatch();
                    List<BmobObject> list1 = new ArrayList<>();
                    for (Photo photo : list) {
                        list1.add(photo);
                    }

                    list1.add(good);
                    batch.deleteBatch(list1);
                    batch.doBatch(listener);
                }
            }
        });
    }

    /**
     * 编辑商品
     *
     * @param good
     * @param photo
     * @param listener
     */
    public void editGood(Good good, Photo photo, QueryListListener<BatchResult> listener) {
        BmobBatch batch = new BmobBatch();

        if (photo != null) {//如果没有修改图片
            photo.setGood(good);
            List<BmobObject> list = new ArrayList<>();
            list.add(photo);
            batch.insertBatch(list);

            good.setThumbnailURL(photo.getFile().getFileUrl());
        }

        List<BmobObject> list = new ArrayList<>();
        list.add(good);

        batch.updateBatch(list);
        batch.doBatch(listener);
    }

    /**
     * 发布商品
     *
     * @param good
     * @param photo
     * @param listener
     */
    public void release(final Good good, final Photo photo, final SaveListener<String> listener) {
        good.setSeller(BaseApplication.getUser());
        good.setThumbnailURL(photo.getFile().getFileUrl());
        good.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    good.setObjectId(objectId);
                    photo.setGood(good);
                    photo.save(listener);
                } else {
                    ToastUtils.show("网络不给力");
                }
            }
        });
    }

    /**
     * 预定商品
     *
     * @param good
     */
    public void reserve(Good good, QueryListListener<BatchResult> listener) {
        if (good.getSeller().equals(BaseApplication.getUser())) {
            ToastUtils.show("自己的商品是不能预定滴(o´ω`o)ﾉ");
            return;
        }

        good.setStatus(Good.BOOKED);
        Order order = new Order();
        order.setGood(good);
        order.setBuyers(BaseApplication.getUser());
        order.setSeller(good.getSeller());
        order.setGoodName(good.getName());
        order.setIntroduction(good.getIntroduction());
        order.setThumbnailURL(good.getThumbnailURL());
        order.setGoodPrice(good.getPrice());

        List<BmobObject> list = new ArrayList<>();
        list.add(order);
        List<BmobObject> list2 = new ArrayList<>();
        list2.add(good);

        BmobBatch batch = new BmobBatch();
        batch.insertBatch(list);
        batch.updateBatch(list2);
        batch.doBatch(listener);
    }

    /**
     * 取消订单
     *
     * @param order
     * @param listener
     */
    public void cancelReserve(Order order, QueryListListener<BatchResult> listener) {
        Good good = order.getGood();
        good.setStatus(Good.NOT_BOOKED);
        order.setStatus(Order.ORDER_CANCELLED);

        List<BmobObject> list = new ArrayList<>();
        list.add(order);
        list.add(good);

        BmobBatch batch = new BmobBatch();
        batch.updateBatch(list);
        batch.doBatch(listener);
    }

    /**
     * 查找用户的所有订单
     *
     * @param skip
     * @param listener
     */
    public void listOrders(int skip, FindListener<Order> listener) {
        BmobQuery<Order> query = new BmobQuery<>();
        query.include("good");
        query.include("seller");
        query.include("buyers");
        query.addWhereEqualTo("buyers", BaseApplication.getUser());
        query.addWhereNotEqualTo("status", Order.ORDER_CANCELLED);
        query.order("-createdAt");
        query.setLimit(10);
        query.setSkip(skip);
        query.findObjects(listener);
    }

    /**
     * 列出评论
     *
     * @param good
     * @param skip
     * @param listener
     */
    public void listComments(Good good, int skip, FindListener<Comment> listener) {
        BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("good", good);
        query.include("owner");
        query.setLimit(10);
        query.order("floor");
        query.setSkip(skip);
        query.findObjects(listener);
    }

    /**
     * 喜欢
     * @param good
     * @param listener
     */
    public void like(Good good, UpdateListener listener) {
        BmobRelation relation = new BmobRelation();
        relation.add(BaseApplication.getUser());
        good.setLikes(relation);
        good.setLikeCounter(good.getLikeCounter() + 1);
        good.update(listener);
    }

    /**
     * 取消喜欢
     * @param good
     * @param listener
     */
    public void cancelLike(Good good, UpdateListener listener) {
        BmobRelation relation = new BmobRelation();
        relation.remove(BaseApplication.getUser());
        good.setLikes(relation);
        good.setLikeCounter(good.getLikeCounter() - 1);
        good.update(listener);
    }

    public class ShpBinder extends Binder {

        public void login(String username, String password, FindListener<User> listener) {
            ShpService.this.login(username, password, listener);
        }

        public void editUser(User user) {
            ShpService.this.editUser(user);
        }

        public void listGoods(int skip, FindListener<Good> listener) {
            ShpService.this.listGoods(skip, listener);
        }

        public void listMyGoods(int skip, FindListener<Good> listener) {
            ShpService.this.listMyGoods(skip, listener);
        }

        public void deleteGood(Good good, QueryListListener<BatchResult> listener) {
            ShpService.this.deleteGood(good, listener);
        }

        public void editGood(Good good, Photo photo, QueryListListener<BatchResult> listener) {
            ShpService.this.editGood(good, photo, listener);
        }

        public void release(final Good good, final Photo photo, final SaveListener<String> listener) {
            ShpService.this.release(good, photo, listener);
        }

        public void reserve(Good good, QueryListListener<BatchResult> listener) {
            ShpService.this.reserve(good, listener);
        }

        public void cancelReserve(Order order, QueryListListener<BatchResult> listener) {
            ShpService.this.cancelReserve(order, listener);
        }

        public void listOrders(int skip, FindListener<Order> listener) {
            ShpService.this.listOrders(skip, listener);
        }

        public void listComments(Good good, int skip, FindListener<Comment> listener) {
            ShpService.this.listComments(good, skip, listener);
        }

        public void like(Good good, UpdateListener listener) {
            ShpService.this.like(good, listener);
        }

        public void cancelLike(Good good, UpdateListener listener) {
            ShpService.this.cancelLike(good, listener);
        }
    }

}
